package untils

import (
	"fmt"
	"github.com/robfig/cron"
	"log"
	"seckill-srv/basic/config"
	"seckill-srv/handler/model"
	"time"
)

func CheckOrderCron() {
	c := cron.New()
	spec := "*/5 * * * * ?"
	err := c.AddFunc(spec, func() {
		log.Println("开始检测订单状态")
		log.Println("当前时间戳：", time.Now().Unix())
		CheckOrderStatus()
	})
	if err != nil {
		fmt.Println("开启定时任务失败:", err)
	}

	c.Start()

	select {}
}

// 检测订单状态
func CheckOrderStatus() {
	//开启事务
	tx := config.DB.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		tx.Rollback()
		return
	}
	//检查订单状态
	var order model.Order
	//1.查询所有订单
	list, err := order.GetOrderList()
	if err != nil {
		log.Printf("订单信息查询失败:%v", err)
		return
	}
	//2.遍历订单
	for _, o := range list {

		err = o.GetOrderBySn(o.OrderSn)
		if err != nil {
			log.Printf("获取订单详情%s失败:%v", o.OrderSn, err)
			return
		}

		// 3. 如果订单状态为待支付，判断是否超时
		if o.PayDurationTime < int(time.Now().Unix()) && o.PayStatus == 1 {
			//回滚库存
			ReturnActivityStock(o.ActivityId, o.OrderNum)
			// 4. 如果超时，更新订单状态为已取消
			o.PayStatus = 3
			err = o.UpdateOrderStatus(tx, o.OrderSn)
			if err != nil {
				log.Printf("更新订单%s状态失败:%v", o.OrderSn, err)
				tx.Rollback()
				return
			}
			err = o.DelOrder(tx, o.OrderSn)
			if err != nil {
				log.Printf("删除订单%s失败:%v", o.OrderSn, err)
				tx.Rollback()
				return
			}
			if err = tx.Commit().Error; err != nil {
				tx.Rollback()
				return
			}
			log.Printf("订单%s超时，已取消", o.OrderSn)
		}
	}

}
